/*
 * @PageName:
 * @Description:
 * @FilePath: /glm-mes-pc/src/store/modules/user.js
 */
import { login, logout, getInfo } from '@/api/login'
import { selectDeptAPI } from '@/api/sampleSalesOrder'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/user_avatar.png'
import router from '@/router'
import { isPhoneNumber } from '@/utils/validate.js'
const useUserStore = defineStore('user', {
	state: () => ({
		token: getToken(),
		// 账号
		name: '',
		// 用户昵称
		nickName: '',
		avatar: '',
		// 部门信息
		deptData: {},
		roles: [],
		permissions: [],
		address: '',
		bankCardNumber: '',
		// 部门列表
		deptList: [],
		// 部门对象
		deptTarget: {}
	}),
	actions: {
		// 登录操作
		async login(userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo)
					.then(({ data: res }) => {
						/* 首次登录, 强制修改密码 */
						if (res?.status) {
							let isPhoneFlag = false
							if (isPhoneNumber(userInfo.username)) {
								isPhoneFlag = true
							}
							const userId = res.sysUser.userId // 用户id
							const userName = isPhoneFlag ? res.sysUser.phonenumber : res.sysUser.userName // 用户名
							localStorage.setItem('firstLogin', res.token)
							router.push({ path: '/force-reset-password', query: { userId, userName, phoneStatus: res.phoneStatus } })
							return false
						}
						/* 存储token */
						setToken(res.token)
						this.token = res.token
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 获取用户信息
		getInfo() {
			return new Promise((resolve, reject) => {
				getInfo()
					.then(({ data: res }) => {
						const user = res.user
						// 用户头像
						const avatar = user.avatar == '' || user.avatar == null ? defAva : user.avatar

						if (res.roles && res.roles.length > 0) {
							// 验证返回的roles是否是一个非空数组
							this.roles = res.roles
							this.permissions = res.permissions
						} else {
							this.roles = ['ROLE_DEFAULT']
						}
						this.name = user.userName
						this.nickName = user.nickName
						this.avatar = avatar
						this.deptData = user.dept
						this.bankCardNumber = user.bankCardNumber
						this.address = user.address
						resolve(res)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 退出系统
		logOut() {
			return new Promise((resolve, reject) => {
				logout(this.token)
					.then(() => {
						this.token = ''
						this.roles = []
						this.permissions = []
						removeToken()
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 获取部门列表信息
		getDeptList() {
			return new Promise((resolve, reject) => {
				selectDeptAPI()
					.then((res) => {
						this.deptList = res.data.map((item) => {
							item.deptId = String(item.deptId)
							this.deptTarget[item.deptId] = item.deptName
							return item
						})
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		}
	}
})

export default useUserStore
